<?php

// 公共助手函数

use Symfony\Component\VarExporter\VarExporter;
use think\exception\HttpResponseException;
use think\Response;
use think\Db;
use think\Request;
use think\Cache;
use sqhlib\Hanzi\HanziConvert;
if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @param int    $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}") : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                $response = Response::create('跨域检测无效', 'html', 403);
                throw new HttpResponseException($response);
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                $response = Response::create('', 'html');
                throw new HttpResponseException($response);
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            $response = Response::create('请求无权访问', 'html', 403);
            throw new HttpResponseException($response);
        }
    }
}
if (!function_exists('dd')) {
    /**
     * 懒人打印法--家伦
     */
    function dd($data)
    {
        print_r($data);die;
    }
}
if (!function_exists('ddlastsql')) {
    /**
     * 打印上一条sql--家伦
     * @param $text
     * @return string
     */
    function ddlastsql()
    {
        echo Db::getLastSql();die;
    }
}
if (!function_exists('encode')) {
    /**
     * 简单对称加密算法之加密
     * @param String $string 需要加密的字串
     * @param String $skey   加密EKY
     * @return String
     */
    function encode($string)
    {
        if (!$string) {
            return false;
        }
        $skey = 'saoma';
        $strArr   = str_split(base64_encode($string));
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value) {
            $key < $strCount && $strArr[$key] .= $value;
        }
        return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
    }
}

if (!function_exists('decode')) {
    /**
     * 简单对称加密算法之解密
     * @param String $string 需要解密的字串
     * @param String $skey   解密KEY
     * @return String
     */
    function decode($string)
    {
        if (!$string) {
            return false;
        }
        $skey = 'saoma';
        $strArr   = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value) {
            $key <= $strCount && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
        }
        return base64_decode(join('', $strArr));
    }
}

if (!function_exists('orderNo')) {
    /**
     * 獲取訂單號
     * @param $text
     * @return string
     */
    function orderNo($type = 1)
    {

        $order_no = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        switch ($type) {
            case '1':
                $count = db('caring_task')->where(['task_no'=>$order_no])->count();
                break;
            case '2':
                $count = db('training_tasks')->where(['task_no'=>$order_no])->count();
                break;
            case '3':
                $count = db('help_task')->where(['task_no'=>$order_no])->count();
                break;
            case '4':
            // 充值積分
                $order_no = 'JF'.$order_no;
                $count = db('recharge')->where(['order_no'=>$order_no])->count();
                break;
            case '5':
                // 訂單id
                $count = db('order')->where(['order_no'=>$order_no])->whereOr(['parent_order_no'=>$order_no])->count();
                break;
            
            default:
                $count = db('caring_task')->where(['task_no'=>$order_no])->count();
                break;
        }
        if ( $count ) {
            return orderNo($type);
        }
        return $order_no;
    }
}

/*
*加积分
*user_id 用戶id
*score 變更積分
*memo 描述
*type 類型類型1關懷任務2培訓任務3簽到4兌換商品5積分充值6互助接單7發佈互助
*relation_id 關聯id（也可以是任務編號）
*/
function addPoints($user_id,$score,$memo,$type,$relation_id,$createtime=0)
{
    $createtime = $createtime?$createtime:time();
    if ( $score == 0 ) {
        return true;
    }
    Db::startTrans();
    try {
        $user = db('user')->where(['id'=>$user_id])->find();
        $score = $score;
        $before = $user['score'];
        $after = $user['score'] + $score;

        if ($after<0) {
            $after = 0;
        }

        $save = [];
        $save['user_id'] = $user_id;
        $save['score'] = $score;
        $save['before'] = $before;
        $save['after'] = $after;
        $save['memo'] = $memo;
        $save['createtime'] = $createtime;
        $save['type'] = $type;
        $save['relation_id'] = $relation_id;

        db('user_score_log')->insertGetId($save);
        $status = db('user')->where(['id'=>$user_id])->update(['score'=>$after,'updatetime'=>$createtime]);

        if ( !$status ) {
            Db::rollback();
            return false;
        }
        // 提交事务
        Db::commit();
    } catch (\Exception $e) {
        // 回滚事务
        Db::rollback();
        return false;
    }
    return true;
}

if (!function_exists('orderPayRechargeSuccess')) {
    /*
    *積分充值支付成功回调
    */
    function orderPayRechargeSuccess($order_no)
    {
        // 看看有没已经处理过这笔订单 
        $count = db('recharge')
                ->where(['order_no'=>$order_no,'pay_status'=>10])
                ->count();

        //不重复处理操作
        if($count == 0) return false;

        $order = db('recharge')
                ->where(['order_no'=>$order_no])
                ->find();

        $time = time();
        Db::startTrans();
        try {

            $update_arr = ['pay_status'=>'20','paytime'=>$time];
            $status = db('recharge')
                    ->where(['id'=>$order['id']])
                    ->update($update_arr);

            if ( !$status ) {
                Db::rollback();
                return false;
            }

            $momo = '線上充值';
            // 加積分
            $status = addPoints($order['user_id'],$order['integral'],$momo,5,$order['order_no'],$time);
            if ( !$status ) {
                Db::rollback();
                return false;
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        return true;
    }
}
if (!function_exists('orderPaySuccess')) {
    /*
    *商品支付成功回调
    */
    function orderPaySuccess($order_no,$transaction_id='')
    {
        // 看看有没已经处理过这笔订单 
        $count = db('order')
                ->where(['order_no'=>$order_no,'pay_status'=>'10'])
                ->whereOr(function ($query) use($order_no) {
                    $query->where(['parent_order_no'=>$order_no,'pay_status'=>'10']);
                })
                ->count();    

        //不重复处理操作
        if($count == 0) return false;
        $order = db('order')
                ->where(['order_no'=>$order_no])
                ->whereOr(['parent_order_no'=>$order_no])
                ->find();

        $order_list = [];
        // 判斷是否是主單回調
        if ( $order_no != $order['parent_order_no'] ) {
            // 子訂單回調
            $order_list[] = db('order')
                            ->where(['order_no'=>$order_no])
                            ->find();
        }else{
            // 主訂單回調
            $order_list = db('order')
                            ->where(['parent_order_no'=>$order_no])
                            ->select();
            
        }
        $time = time();
        Db::startTrans();
        try {
            foreach ($order_list as $key => $value) {
                $update_arr = ['pay_status'=>'20','paytime'=>$time,'order_status'=>'20','transaction_id'=>$transaction_id];
                $status = db('order')
                        ->where(['id'=>$value['id']])
                        ->update($update_arr);

                if ( !$status ) {
                    Db::rollback();
                    return false;
                }
                if ( $value['total_integral'] >0 ) {
                    $momo = '兌換商品';
                    // 加積分
                    $status = addPoints($value['user_id'],-$value['total_integral'],$momo,4,$value['order_no'],$time);
                    if ( !$status ) {
                        Db::rollback();
                        return false;
                    }
                }

                $deduct_stock_array = [];
                $order_goods = db('order_goods')->where(['order_id'=>$value['id']])->select();
                foreach ($order_goods as $kg => $vg) {
                    db('goods_spec')->where(['goods_id'=>$vg['goods_id'],'goods_spec_id'=>$vg['goods_spec_id']])->setDec('stock_num',$vg['total_num']);
                    db('goods')->where(['goods_id'=>$vg['goods_id']])->setInc('sales_actual',$vg['total_num']);

                    if ( isset($deduct_stock_array[$vg['goods_id']]) ) {
                        $deduct_stock_array[$vg['goods_id']] += $vg['total_num'];
                    }else{
                        $deduct_stock_array[$vg['goods_id']] = $vg['total_num'];
                    }
                }

                foreach ($deduct_stock_array as $kd => $vd) {
                    $stock_num  = db('goods_spec')->where(['goods_id'=>$kd])->sum('stock_num');
                    $negative_goods_spec = db('goods_spec')->where(['goods_id'=>$kd,'stock_num'=>['lt',0]])->update(['stock_num'=>0]);
                    // 库存不足下架
                    if ( !$stock_num ) {
                        db('goods')->where(['goods_id'=>$kd])->update(['goods_status'=>'20']);
                    }
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        return true;
    }
}
if (!function_exists('addShopMoney')) {
    /**
     * [addShopMoney 增加商家金額]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-19T02:17:28+0800
     * @param      [type]                   $shop_id     [商家id]
     * @param      [type]                   $money       [金額]
     * @param      [type]                   $memo        [描述]
     * @param      [type]                   $relation_id [關聯ID]
     * @param      integer                  $createtime  [增加時間]
     */
    function addShopMoney($shop_id,$money,$memo,$relation_id,$createtime=0)
    {
        $createtime = $createtime?$createtime:time();
        if ( $money == 0 ) {
            return true;
        }
        Db::startTrans();
        try {
            $manystore_shop = db('manystore_shop')->where(['id'=>$shop_id])->find();
            $money = $money;
            $before = $manystore_shop['money'];
            $after = $manystore_shop['money'] + $money;

            if ($after<0) {
                $after = 0;
            }

            $save = [];
            $save['shop_id'] = $shop_id;
            $save['money'] = $money;
            $save['before'] = $before;
            $save['after'] = $after;
            $save['memo'] = $memo;
            $save['createtime'] = $createtime;
            $save['relation_id'] = $relation_id;

            db('shop_money_log')->insertGetId($save);
            $status = db('manystore_shop')->where(['id'=>$shop_id])->update(['money'=>$after,'update_time'=>$createtime]);

            if ( !$status ) {
                Db::rollback();
                return false;
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        return true;
    }
}
if (!function_exists('sendMessage')) {
    /**
     * [sendMessage 發送消息]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-26T15:06:07+0800
     * @param      [type]                   $type        [消息類型：0全体消息1个体消息]
     * @param      [type]                   $title       [标题]
     * @param      [type]                   $message     [站内信内容]
     * @param      integer                  $user_id     [用戶id]
     * @param      integer                  $source      [消息類型，1系統消息2求助訂單3商城訂單4積分訂單5義工審核6商家入駐7文章更新]
     * @param      integer                  $relation_id [關聯id]
     * @return     [type]                                [description]
     */
    function sendMessage($type,$title,$message,$user_id=0,$source=0,$relation_id=0)
    {
        if ( $source == 7 ) {
            $message_template = db('message_template')->where(['type'=>abs($relation_id)])->find();
            if ( $message_template ) {
                $title = $message_template['title'];
            }
        }
        $time = time();
        $message_id = db('message')->insertGetId(['admin_id'=>0,'message'=>'','type'=>$type,'createtime'=>$time,'title'=>$title,'message'=>$message,'relation_id'=>$relation_id,'source'=>$source]);
        if ( $message_id  ) {
            db('user_message')->insertGetId(['user_id'=>$user_id,'message_id'=>$message_id]);
        }
        return true;
    }
}
if (!function_exists('setArticleHistory')) {
    /**
     * [setArticleHistory 存儲用戶瀏覽記錄]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-26T16:33:47+0800
     * @param      [type]                   $user_id     [用戶id]
     * @param      [type]                   $type        [類型1大灣區資訊2大灣區調查3工聯中心4活動5互助廣場]
     * @param      [type]                   $relation_id [關聯id]
     */
    function setArticleHistory($user_id,$type,$relation_id)
    {
        $time = time();
        db('article_history')->insertGetId(['user_id'=>$user_id,'type'=>$type,'relation_id'=>$relation_id,'createtime'=>$time]);
        return true;
    }
}
/*
排序一维数组
*/
if (!function_exists('array_sort')) {
    function array_sort($arr,$type='asc'){
        $keysvalue = $new_array = array();
        foreach ($arr as $k=>$v){
            $keysvalue[$k] = $k;
        }
        if($type == 'asc'){
            asort($keysvalue);
        }else{
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k=>$v){
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }
}
/*
排序二维数组
*/
if (!function_exists('array_sort_two')) {
    function array_sort_two($arr,$keys,$type='asc'){
        $keysvalue = $new_array = array();
        foreach ($arr as $k=>$v){
            $keysvalue[$k] = $v[$keys];
        }
        if($type == 'asc'){
            asort($keysvalue);
        }else{
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k=>$v){
            $new_array[$k] = $arr[$k];
        }
        $new_array_buf = [];
        foreach ($new_array as $key => $value) {
            $new_array_buf[] = $value;
        }
        return $new_array_buf;
    }
}
if ( !function_exists('refund') ) {
    function refund($order_id)
    {
        $deduct_stock_array = [];
        $order_goods = db('order_goods')->where(['order_id'=>$order_id])->select();
        foreach ($order_goods as $kg => $vg) {
            db('goods_spec')->where(['goods_id'=>$vg['goods_id'],'goods_spec_id'=>$vg['goods_spec_id']])->setInc('stock_num',$vg['total_num']);
            db('goods')->where(['goods_id'=>$vg['goods_id']])->setDec('sales_actual',$vg['total_num']);

            if ( isset($deduct_stock_array[$vg['goods_id']]) ) {
                $deduct_stock_array[$vg['goods_id']] += $vg['total_num'];
            }else{
                $deduct_stock_array[$vg['goods_id']] = $vg['total_num'];
            }
        }

        foreach ($deduct_stock_array as $kd => $vd) {
            $stock_num  = db('goods_spec')->where(['goods_id'=>$kd])->sum('stock_num');
            $negative_goods_spec = db('goods_spec')->where(['goods_id'=>$kd,'stock_num'=>['lt',0]])->update(['stock_num'=>0]);
            // 库存不足下架
            if ( !$stock_num ) {
                db('goods')->where(['goods_id'=>$kd])->update(['goods_status'=>'20']);
            }else{
                db('goods')->where(['goods_id'=>$kd])->update(['goods_status'=>'10']);
            }
        }
    }
}
if ( !function_exists('pointsOrderSuccess') ) {
    function pointsOrderSuccess($order_no)
    {
        $time = time();
        // 主訂單回調
        $order = db('order')
                    ->where(['parent_order_no'=>$order_no])
                    ->find();

            $deduct_stock_array = [];
            $order_goods = db('order_goods')->where(['order_id'=>$order['id']])->select();
            foreach ($order_goods as $kg => $vg) {
                db('goods_spec')->where(['goods_id'=>$vg['goods_id'],'goods_spec_id'=>$vg['goods_spec_id']])->setDec('stock_num',$vg['total_num']);
                db('goods')->where(['goods_id'=>$vg['goods_id']])->setInc('sales_actual',$vg['total_num']);

                if ( isset($deduct_stock_array[$vg['goods_id']]) ) {
                    $deduct_stock_array[$vg['goods_id']] += $vg['total_num'];
                }else{
                    $deduct_stock_array[$vg['goods_id']] = $vg['total_num'];
                }
            }

            foreach ($deduct_stock_array as $kd => $vd) {
                $stock_num  = db('goods_spec')->where(['goods_id'=>$kd])->sum('stock_num');
                $negative_goods_spec = db('goods_spec')->where(['goods_id'=>$kd,'stock_num'=>['lt',0]])->update(['stock_num'=>0]);
                // 库存不足下架
                if ( !$stock_num ) {
                    db('goods')->where(['goods_id'=>$kd])->update(['goods_status'=>'20']);
                }
            }

        $status = addPoints($order['user_id'],-$order['total_integral'],'兌換商品','4',$order_no,$time);
        return $status;
    }
}

//检查参数类型
function checkValueType($value, $type)
{
    switch ($type) {
        case 'int':
            return is_int(intval($value));
        case'bool':
            return is_bool($value);
        case'string':
            return is_string($value);
        case'string_list':
            if (is_array($value)) {
                foreach ($value as $item) {
                    if (!is_string($item)) {
                        return false;
                    }
                }
                return true;
            } else {
                return false;
            }
        case 'int_list':
            if (is_array($value)) {
                foreach ($value as $item) {
                    if (!is_int(intval($item))) {
                        return false;
                    }
                }
                return true;
            } else {
                return false;
            }
        case'array':
            return is_array($value);
        case 'phone_number':
            $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
            return preg_match($rule, $value);
        case 'number':
            return is_numeric($value);
        default:
            return false;
    }


}

//检查列表没有重复元素
function checkHasSameValueInList($list)
{
    $values = array_count_values($list);
    foreach ($values as $item) {
        if ($item > 1) {
            return true;
        }
    }
    return false;
}

//统计字符数量
function getWordNum($str){
    $match=null;
    // 将字符串分解为单元
    preg_match_all('/./us', $str, $match);
    // 返回单元个数
    return count($match[0]);

}

//中英文混合字符裁剪
//$ch代表中文占多少个字符
function subFormStr($string , $length ,$ch=1) {
    $num = 1;
    $t = 0;
    $x = 1;
    $result = [['count'=>0,'str'=>'']];
    $strlen = mb_strlen($string);
    while ($strlen) {
        $array[$t] = mb_substr($string, 0, 1, "UTF-8");
        $string = mb_substr($string, 1, $strlen, "UTF-8");
        $strlen = mb_strlen($string);
        if ($result[($x - 1)]['count'] >= $length) {
            $x++;
            $num++;
            $result[($x - 1)]['count'] = 0;
            $result[($x - 1)]['str'] = '';
        }
        if (strlen($array[$t]) > 1) {
            /**  一个汉字占两个位置  **/
            $result[($x - 1)]['count'] +=$ch;
        } else {
            $result[($x - 1)]['count'] += 1;
        }
        if ($x == 1) {
            $result[($x - 1)]['str'] .= $array[$t];
        } else {
            $result[($x - 1)]['str'] .= $array[$t];
        }
        $t++;
    }
    return [count($result),array_column($result,'str')];
}

function checkPrivilege($url, $strict = true)
{
    
    return true;
    
}

/**
 * 获取当前域名及根路径
 * @return string
 */
function base_url()
{
    static $baseUrl = '';
    if (empty($baseUrl)) {
        $request = Request::instance();
        $subDir = str_replace('\\', '/', dirname($request->server('PHP_SELF')));
        // $baseUrl = $request->scheme() . '://' . $request->host() . $subDir . ($subDir === '/' ? '' : '/');
        $baseUrl = $request->scheme() . '://' . $request->host().'/' ;
    }
    return $baseUrl;
}

function getAreaNameList()
{
    $arr = Cache::get('AreaNameList');
    if(empty($arr)){
        $list = db('area')->field('id,name')->select();
        
        foreach($list as $k =>$v){
            $arr[$v['id']] = $v['name'];
        }
        Cache::set('AreaNameList',$arr,600);
    }
   
    return $arr;
} 

function getCenterNameList()
{
    $arr = Cache::get('CenterNameList');
    if(empty($arr)){
        
        $list = db('area')->where('pid',0)->field('id,name')->select();
        
        foreach($list as $k =>$v){
            $arr[$v['id']] = $v['name'];
        }
        Cache::set('CenterNameList',$arr,600);
    }
   
    return $arr;
} 

function statisQustion($qid = 14)
{
    $key = 'statisQustion'.$qid;
    $arr = Cache::get($key);
    if(empty($arr)){
        $arr = db('child_data_log')->where(['fid'=>$qid])->select();
        Cache::set($key,$arr,600);
    }
    return $arr;
    
}

function statisQustionByChose($qid = 14,$cid,$type,$chose,$value = '')
{
    $data = statisQustion($qid);
    $total = 0;
    if(empty($data)){
        return 0;
    }
    foreach($data as $k => $v){
        if($type != $v['type']){
            continue;
        }

        if($type == 2){

        }else{
            if($cid != $v['cid']){
                continue;
            }
           
            if($chose != $v['choice']){
                continue;
            }
            if($type == 4){
                if($value != $v['value']){
                    continue;
                }
            }
        }
        
        $total++;
    }
    
    return $total;
}

function getNumRatio($a,$b,$scale = 2){
    if(abs($a) <1 || abs($b) <1){
        return 0;
    }
    $num = bcdiv($a,$b,$scale) * 100;
    return $num;
}

function statisQustionType_2($qid = 14,$cid,$type = 2)
{
    $data = statisQustion($qid);
    
    if(empty($data)){
        return '';
    }
    $arr = [];
    foreach($data as $k => $v){
        // if(in_array($v['did'],$arr)){

        // }
        if($v['type'] != $type ){
            continue;
        }

        if($cid != $v['cid']){
            continue;
        }
        $arr[$v['did']][$v['choice']] = $v['value'];
    }
    $str_arr = [];
    foreach($arr as $list){
        $str_arr[] = implode(',',$list);
    }
    
    return $str_arr;
}

function cnChangeStr($str = '')
{   
    $arr = [];
    $arr['cn_f'] =  HanziConvert::convert($str);
    $arr['cn'] =  HanziConvert::convert($str,true);
    return $arr;
}



